<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"-->
<!--        integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">-->
  <link rel="stylesheet" href="../css/pet-store-plus.css">
<!--  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">-->
  <script src="/js/chart.js"></script>
<!--  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>-->
<!--  jsdeliverjquery.min-->
  <script src="/js/jsdeliverjquery.min.js"></script>
<!--  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>-->
  <title>消息</title>

</head>
<body>

<div th:replace="seller_commom"></div>

<div class="content" id="content">
  <div  class="msgList">
    <table id="msgTab">
      <tr th:each="entry: ${userList}" class="msgrows">
        <td th:text="${entry.key}" id="userid"></td>
<!--        <td th:text="${entry.value}" id="msgCount"></td>-->
      </tr>
    </table>
  </div>
  <div class="chat" style="grid-column: span 4;grid-row:span 8" >
  <div class="chat-container">
    <div class="chat-display">
      <!-- 对话展示框将在这里 -->
    </div>
    <div class="chat-input">
      <input type="text" id="message-input" placeholder="请输入内容">
      <div>
        <button id="submitBtn" class="Button" onclick="sendMsg()">发送</button>
      </div>
      </div>

  </div>
  </div>
  <script th:inline="javascript">
    const wsMap = {}; // 用于存储WebSocket对象的Map
    var ws;

    const chatDisplay = document.querySelector('.chat-display');
    const messageInput = document.getElementById('message-input');
    const submitBtn = document.getElementById('submit-btn');
    const chatcontainer=document.querySelector('.chat-container');
    const messages=[];//改了{}
    var customerID;
    var username;
    // var customerID=document.getElementById("userid").textContent;//加上了
    // console.log(customerID);
    const msgList=document.querySelector(".msgrows");

    $('.msgrows').on('click', function() {
      chatcontainer.style.display='block';
      // 获取点击行在表格中的索引（从0开始计数）
      const rowIndex = $(this).index();
      username = customerID;
       customerID = $(this).find('#userid').text();

      var table = document.getElementById("msgTab");

// 获取表格中的所有行
      var rows = table.getElementsByClassName("msgrows");
      $(this).find('#msgCount').text('0');


// 遍历每一行
      Array.from(rows).forEach(function(row) {
        row.classList.remove("highlight");
      });


      // 将点击的行添加高亮样式
      this.classList.add("highlight");

      // 输出当前行的 userid
      console.log('User ID:', customerID);

      // 现在您可以使用rowIndex执行任何需要的操作
      console.log('Clicked row index:', rowIndex);
      const Url='ws://localhost:8080/chat/'+customerID;

      createWebSocket(Url);

    });

    // msgList.addEventListener('click',function () {

    window.addEventListener('beforeunload', function() {//离开页面时关闭Websocket连接
      ws.close();
      const url='/admin/closeChat?customerId='+customerID;
      fetch(url,{
        method:'GET'
      }).then(response=>{
        if(response.ok){
          console.log('response.ok');
        }
        return response.json;
      }).then(data=>{
        console.log(data);
        console.log('closeChat');
      })

    });

    function createWebSocket(url) {
      if(ws!=null){
        ws.close();
      }

      // if (!wsMap[url]) {
         ws = new WebSocket(url);
        wsMap[url] = ws;
        ws.userType="admin";
        // 设置WebSocket事件处理
        ws.onopen = function(event) {
          console.log('WebSocket 连接成功');
        };
        ws.onclose=function (event) {
        console.log('close');

        var url = `/admin/closeChat?customerId=` + username;

        console.log("关闭的是"+ username);
        fetch(url,{
          method:'GET'
        }) .then(response => response.json())
                .catch(error => {
                  console.error('请求发送失败:', error);
                });
      }

        ws.onmessage = function(event) {
          chatDisplay.innerHTML = '';
          // 处理接收到的消息
          const msg = JSON.parse(event.data);
          console.log('onmessage');

          console.log(event.data)
          console.log("msg" + msg);

          msg.forEach(function (message) {
            const content = message.content;
            console.log("content" + content)//ok,message为数组
            const time = new Date(message.createTime).toLocaleString();
            const userId = message.username;
            // console.log()
            const adminId = message.adminname;
            const direction = message.direction;
            const messageItem = document.createElement('li');
            const name = direction == 1 ? userId : adminId;
            messageItem.textContent = `${time}   ${name}: ${content}`;
            messageItem.style.color = direction === 1 ? 'blue' : 'green'; // 根据方向设置消息颜色

            // 将消息添加到消息列表中
            console.log("messageItem" + messageItem);
            chatDisplay.appendChild(messageItem);
          })


        };

        // 其他事件处理逻辑

      // }
    }

    function sendMsg(){
      var time = Date.now();
      var date = new Date(time);

      var year = date.getFullYear();
      var month = String(date.getMonth() + 1).padStart(2, '0');
      var day = String(date.getDate()).padStart(2, '0');
      var hours = String(date.getHours()).padStart(2, '0');
      var minutes = String(date.getMinutes()).padStart(2, '0');
      var seconds = String(date.getSeconds()).padStart(2, '0');

// 构造日期时间字符串
      var formattedDate = year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
      console.log(formattedDate)
      var adminid = /*[[${session.loginAdmin.adminname}]]*/ null;
      console.log('adminid='+adminid);
      console.log("?");//按钮触发失败
      const message = messageInput.value;
      let sendObject=JSON.stringify({
        content:message,
        createTime:formattedDate,
        username:customerID,
        adminname:adminid,
        direction:0 });
      console.log(sendObject);
      ws.send(sendObject);
      // const messageItem = document.createElement('li');
      // messageItem.textContent = message;
      // messageItem.style.color ='green'; // 根据方向设置消息颜色
      // // 将消息添加到消息列表中
      // document.getElementById('message-list').appendChild(messageItem);
      messageInput.value = ''; // 清空输入框
    }

    // submitBtn.addEventListener('click', function() {
    //
    // });
  </script>
</div>

</body>
</html>